package com.yupi.springbootinit.job.once;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONNull;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yupi.springbootinit.esdao.PostEsDao;
import com.yupi.springbootinit.model.dto.post.PostEsDTO;
import com.yupi.springbootinit.model.entity.Post;
import com.yupi.springbootinit.service.PostService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 全量同步帖子到 es
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://yupi.icu">编程导航知识星球</a>
 */
// todo 取消注释开启任务
    //以为springboot项目启动的时候会自动注册bean对象，所以，如果加了Component注解就会自动将数据插入数据库
//@Component
@Slf4j
public class FetchInitPostList implements CommandLineRunner {

    @Resource
    private PostService postService;


    @Override
    public void run(String... args) {
        String json ="{\"pageSize\":12,\"sortOrder\":\"descend\",\"tags\":[\"Java\"],\"current\":1,\"reviewStatus\":1,\"category\":\"文章\",\"hiddenContent\":true,\"priorityList\":[999,9999],\"sorterList\":[{\"field\":\"priority\",\"asc\":false},{\"field\":\"createTime\",\"asc\":false}]}";
        String url  = "https://api.code-nav.cn/api/course/list/page/vo";
        String result = HttpRequest.post(url)
                .body(json)
                .execute().body();
        Map<String,Object> map = JSONUtil.toBean(result,Map.class);
        JSONObject data = (JSONObject)map.get("data");
        JSONArray records = (JSONArray) data.get("records");
        //1:title 2:content 3:tag
        List<Post> postList = new ArrayList<>();
        for (Object record : records) {
            JSONObject tempjson = (JSONObject)record;
            Post post = new Post();
            post.setTitle(tempjson.getStr("title"));
            post.setContent(tempjson.getStr("content"));
            Object tags = tempjson.get("tags");
            if(!(tags instanceof JSONNull)){
                JSONArray jsonArray = (JSONArray) tempjson.get("tags");
                List<String> tagList = jsonArray.toList(String.class);
                post.setTags(JSONUtil.toJsonStr(tagList));
            }else {
                post.setTags("");
            }
            post.setUserId(1L);
            postList.add(post);
        }
        final boolean save = postService.saveBatch(postList);
        log.info("初始化插入数据："+save);
    }
}
